<?php

require_once "MainController.php";

/**
 * Contrôleur du A Propos
 *
 * @package Controller
 * @author  nroche <nicolas.roche42@gmail.com>
 *
 */
class ProfileController extends MainController
{
    /**
     * Action par défaut
     *
     * @return null
     */
    public function indexAction() {

        // .js
        $this->view->headScript()->appendFile($this->view->baseUrl() . "/js/profile.js");

        $this->view->params = array();

        if (isset($_SESSION['user']['params']['mg']['cols'])) {
//             $defaultParamsArr = new Array();
        }
        else {
//             $this->view->params['columns'] = (2|4|8|32|64);


            // nomFR,note,moy,format,qu,lang,ss,vu
//             $_SESSION['user']['params']['mg']['cols'] = (2|4|8|32|64);

//             var_dump($_SESSION['user']['params']['columns']);die;
        }

        if (isset($_SESSION['user']['params']['mg']['addmovie'])) {

        }
        else {
            //format,qualite,lang,ss,vu
//             $_SESSION['user']['params']['mg']['addmovie'] = array('','',0,0,0);
//             $this->view->params['addmovie'] = array('','',0,0,0);


        }

        $this->view->params['columns'] = array(
                'nameFr' => false,
                'myRating' => true,
                'avgRating' => true,
                'format' => true,
                'quality' => false,
                'languages' => true,
                'subtitles' => true,
                'watched' => false,
        );

        $this->view->params['addmovie'] = array(
                'format' => 0,
                'languages' => 0,
                'subtitles' => 0,
                'watched' => true,
        );

//         var_dump($this->view->params);die;

    }

    /**
     * Appel: profile/savepublicname/publicname/?
     */
    public function savepublicnameAction() {

        $params = $this->_request->getParams();

        if (!isset($params['publicname'])) {
            $this->_response->clearBody();
            $this->_response->clearHeaders();
            $this->_response->setHttpResponseCode(406);
            return;
        }

        $idUser = $this->_sessionManager->getUserId();

        $newPublicName = $params['publicname'];

        if (strlen($newPublicName) < 2 || strlen($newPublicName) > 12) {
            $res = array(
                    'success' => false,
                    'msg' => 'Le pseudo doit être entre 2 et 12 caractères (lettres et chiffres)',
            );
            $this->_helper->json($res);
            return;
        }

        if (!ctype_alnum($newPublicName)) {
            $res = array(
                    'success' => false,
                    'msg' => 'Caractères autorisés : lettres et chiffres',
            );
            $this->_helper->json($res);
            return;
        }

        $userMapper = Adapter::getUserMapper();
        if ($userMapper->userExists_byPublicName($newPublicName)) {
            $res = array(
                    'success' => false,
                    'msg' => 'Pseudo déjà pris',
            );
            $this->_helper->json($res);
            return;
        }

        $data = array('publicName' => $newPublicName);
        $userMapper->updateUser($idUser, $data);

        $_SESSION['user']['publicName'] = $newPublicName;

        $res = array(
                'success' => true,
                'msg' => 'Mis-à-jour',
        );
        $this->_helper->json($res);
    }


    /**
     * Appel: profile/changepass/oldpass/?/newpass/?
     */
    public function changepassAction() {

        try {

            $params = $this->_request->getParams();

            if (!isset($params['oldpass']) || !isset($params['newpass'])) {
                $this->_response->clearBody();
                $this->_response->clearHeaders();
                $this->_response->setHttpResponseCode(406);
                return;
            }

            $idUser = $this->_sessionManager->getUserId();

            $config = Zend_Registry::get('Zend_Config');
            $key = $config["security_key"];

            $userMapper = Adapter::getUserMapper();

            $oldPass = $params['oldpass'];
            $newPass = $params['newpass'];

            $return_success = false;
            $return_msg = '';

            if ($oldPass == $newPass) {
                $return_msg = 'Le mot de passe n\'a pas changé';
            }
            elseif (strlen($newPass) < 6 || strlen($newPass) > 20) {
                $return_msg = 'Le mot de passe doit faire entre 6 et 20 caractères';
            }
            elseif (!$userMapper->userExists_byIdAndPass($idUser, $oldPass, $key)) {
                $return_msg = 'Mauvais mot de passe)';
            }
            else {
                $salt = $this->generateRandomString(5);
                $newPassInDB = sha1($key . $salt . $newPass);

                $data = array('salt' => $salt, 'password' => $newPassInDB);
                $userMapper->updateUser($idUser, $data);

                $return_msg = 'Mis-à-jour';
                $return_success = true;
            }
        }
        catch (Exception $e) {
            $return_msg = "Erreur interne";
        }

        // Retour
        $res = array(
                'success' => $return_success,
                'msg' => $return_msg,
        );
        $this->_helper->json($res);
    }

    // TODO : mettre dans un utils/tools
    private function generateRandomString($lenght)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randstring = '';
        for ($i = 0; $i < $lenght; $i++)
        {
            $randstring .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randstring;
    }


}

